<template>
  <x-dialog
    :title="title"
    :close-on-click-modal="false"
    :show.sync="visible"
    v-if="visible"
    class="supplier-dialog"
    append-to-body
    width="1000px"
    :before-close="handleClose"
    @onCancel="handleClose"
    @onSubmit="handleSubmit"
  >
    <div class="main-content">
      <div class="tree-area">
        <el-tree
          :props="treeProps"
          ref="tree"
          node-key="id"
          default-expand-all
          :highlight-current="true"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :data="postTreeData"
          check-strictly
          @node-click="handleNodeClick"
        ></el-tree>
      </div>
      <div class="table-area">
        <!-- <x-filter @search="handleSearch" @reset="handleReset" class="dialog-fliter">
        <x-filter-item label="用户名称">
          <el-input v-model="searchParams.uesrname" ></el-input>
        </x-filter-item>
      </x-filter> -->
        <x-table
          :data-source="tableData"
          size="mini"
          @on-change="handleTableChange"
          @on-selection-change="handleSelectionChange"
          :pagination="pagination"
          :loading="loading"
          :row-key="'id'"
          :height="338"
        >
          <el-table-column type="selection" width="60"></el-table-column>
          <el-table-column prop="realName" label="姓名"></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
          <el-table-column prop="deptId" label="岗位"></el-table-column>
          <el-table-column prop="postId" label="部门"></el-table-column>
        </x-table>
      </div>
      <div class="btn-area">
        <div>
          <el-button type="primary" icon="el-icon-right" circle @click="handleChoose"></el-button>
        </div>
        <div>
          <el-button type="primary" icon="el-icon-back" circle @click="handleCancelChoose"></el-button>
        </div>
      </div>
      <div class="selected-area">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <el-checkbox-group v-model="checkList" @change="handleCheckOneChange">
          <div :key="row.id" v-for="row in selectedData">
            <el-checkbox :label="row.id">{{ row.name }}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>
  </x-dialog>
</template>
<script>
  // import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@/common/mixins'
  import { TableListMixin, QueryDictMixin, PermissionsMixin } from '@package/utils'
  import { mapState } from 'pinia'
  import { pinias } from '@/common/pinia'
  import { EnumApiCode } from '../../../../../../globalEnum'
  import { listOrgUserUrl as listUrl, apiDeptTree } from '../api'

  const { login } = pinias
  export default {
    components: {},
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    props: {
      title: {
        type: String,
        default: '用户选择'
      },
      initSelectedData: {
        type: Array,
        default: () => []
      }
    },
    watch: {
      initSelectedData: {
        handler(val) {
          this.selectedData = [...val]
        },
        deep: true,
        immediate: true
      }
    },
    computed: {
      ...mapState(login, ['user']),
      isIndeterminate() {
        const checkedCount = this.checkList.length
        return checkedCount > 0 && checkedCount < this.selectedData.length
      },
      checkAll: {
        get() {
          const checkedCount = this.checkList.length
          return checkedCount > 0 && checkedCount === this.selectedData.length
        },
        set() {
          this.checkList = this.selectedData
        }
      }
    },
    data() {
      return {
        visible: false,
        searchParams: {
          deptId: '',
          uesrname: ''
        },
        listUrl,
        tableData: [],
        selectionRows: [], // 表格选中的数据
        selectedData: [], // 最后确认选中的用户
        checkList: [], //  选中用户复选框
        treeProps: {
          label: 'deptName',
          children: 'children'
        },
        postTreeData: [],
        currentNode: {}
      }
    },
    methods: {
      show() {
        this.visible = true
        this.loadTreeData()
        this.loadData()
      },
      handleNodeClick(node) {
        this.currentNode = node
        this.handleSearch({ deptId: this.currentNode.id })
      },
      async loadTreeData() {
        this.treeLoading = true
        const { orgId } = this.user.mainPost
        const { data, code, msg } = await apiDeptTree({ orgId })
        this.treeLoading = false
        if (code === EnumApiCode.Success) {
          this.postTreeData = data
          if (this.postTreeData?.length) {
            this.currentNode =
              this.currentNode?.id && this.$refs.tree.getNode(this.currentNode.id)
                ? this.currentNode
                : this.postTreeData[0]
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.currentNode.id)
            })
            this.handleSearch({ deptId: this.currentNode.id })
          }
        } else {
          this.$message.error(msg)
        }
      },
      handleSearch(val) {
        this.queryParam = { ...this.searchParams, ...val }
        this.loadData()
      },
      handleReset() {
        this.resetSearch()
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectionRows = rows
      },
      handleCheckAllChange(val) {
        const selectedIds = this.selectedData.map((s) => s.id)
        this.checkList = val ? selectedIds : []
      },
      handleCheckOneChange(value) {
        const checkedCount = value.length
        // this.checkAll = checkedCount === this.selectedData.length
      },
      handleChoose() {
        const selectedIds = this.selectedData.map((s) => s.id)
        this.selectionRows.forEach((row) => {
          if (!selectedIds.includes(row.id)) {
            this.selectedData.push({
              id: row.id,
              name: row.realName
            })
          }
        })
      },
      handleCancelChoose() {
        this.selectedData = this.selectedData.filter((s) => {
          return !this.checkList.includes(s.id)
        })
        this.checkList = []
      },
      // 弹窗关闭
      handleClose() {
        this.checked = null
        this.selectionRows = []
        this.visible = false
      },
      // 弹窗确定
      handleSubmit() {
        if (this.selectedData.length) {
          this.$emit('confirm', this.selectedData)
          this.handleClose()
        } else {
          this.$message.error('请至少选择一条数据点击确定')
        }
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      }
    }
  }
</script>
<style lang="scss" scoped>
  .supplier-dialog {
    .dialog-fliter {
      // margin-bottom: 10px;
    }
    .x-table-container {
      height: 380px;
    }
    ::v-deep .x-filter-container {
      background: none;
      box-shadow: none;
      border: none;
    }
    ::v-deep .x-filter-content {
      padding: 0;
    }
    .main-content {
      display: flex;
      .tree-area {
        width: 200px;
        border: 1px solid #ccc;
      }
      .table-area {
        flex: 1;
        // padding: 0 10px;
        border: 1px solid #ccc;
        border-left: none;
        ::v-deep .el-pagination__jump {
          margin-left: 0;
          padding-right: 6px;
        }
      }
      .btn-area {
        justify-content: center;
        display: flex;
        flex-direction: column;
        padding: 10px;
        div {
          margin-top: 10px;
        }
      }
      .selected-area {
        width: 200px;
        padding: 8px;
        border: 1px solid #ccc;
      }
    }
  }
</style>
